<?php 

/**
 * 退换货管理
 * @copyright   Copyright (c) 2006 - 2010 DZH 友拓软件友拓通
 * @category    基本信息
 * @package   Model
 * @author     庄敏学
 * @version  2.1,2012-07-22
 */

class ReturnSaleOrderPublicModel extends RelationCommonModel {
	/// 定义真实表名
	protected $tableName = 'return_sale_order';
	/// 定义表关联
	protected $_link	 = array('detail' => 
									array(
										'mapping_type'	=> HAS_MANY,
										'foreign_key' 	=> 'return_sale_order_id',
										'class_name'	=> 'ReturnSaleOrderDetail',
									)
								);	
	/// 自动验证设置
	protected $_validate	 =	 array(
			array("return_sale_order_type",'require','require',1),
			array("client_id",'require','require',1),
			array("basic_id",'require','require',0),
			array("currency_id",'require','require',1),
			array("return_order_date",'require','require',1),
			array("",'_validDetail','require',1,'validDetail'),
			array("",'validSaleInfo','require',1,'callbacks'), 	
			array('','validQuantity','',1,'callbacks'), 
			array('','validQuantityForSale','',1,'callbacks'),  
		);
	protected $_validDetail	 =	 array(
			array("product_id",'require','require',1),
			array("color_id",'require','require',0),
			array("size_id",'require','require',0),
			array("quantity",'currency','double',1),
			array("capability",'pst_integer','pst_integer',0),
			array("dozen",'pst_integer','pst_integer',0),
			array("price",'double','double',1),
			array('price','currency','valid_money',1),
			array('warehouse_id','require','require',0),
			array('is_use','pst_integer','pst_integer',1),
			array("discount",'double','double',2), 
			array("discount",array(0,1),'between',2,'between'),
		);	
	protected $_validSale	 =	 array(
			array("product_id",'require','require',1),
			array("color_id",'require','require',0),
			array("size_id",'require','require',0),
			array("quantity",'currency','double',1),
			array("capability",'z_integer','z_integer',0),
			array("dozen",'z_integer','z_integer',0),
			array("price",'double','double',1),
			array('price','currency','valid_money',1),
			array('warehouse_id','require','require',0),
			array("discount",'double','double',2), 
			array("discount",array(0,100),'between',2,'between'),
		);	
	/// 自动填充
	protected $_auto = array(
							array("create_time ", "date", 1, "function", "Y-m-d H:i:s"), // 创建时间	
							array("update_time ", "date", 2, "function", "Y-m-d H:i:s"), // 更新时间					
						);	
						
	public function validSaleInfo($data){
		if($data['return_sale_order_type']==2){
			$valid	=	'_validSale';
			return $this->_moduleValidationDetail(&$this,&$data,'sale',&$valid);  
		}     
	}
/**
	 * 
	 * 箱数验证 是否可输入小数
	 * @param unknown_type $data
	 */
	public function validQuantityForSale($data){
	$quantity_format	= C('quantity_format');
		foreach($data['sale'] as $key=>$val){
			$sum	= Floatval($val['quantity'])*Floatval($val['capability']);
			if($quantity_format==2){
				if(intval($sum)!=$sum){
					$error['name']	= 'sale['.$key.'][quantity]';
					$error['value']	= L('quantity_format_error');
					$this->error[] = $error;	
				}
			}elseif(intval($val['quantity'])!=$val['quantity']){
				$error['name']	= 'sale['.$key.'][quantity]';
				$error['value']	= L('quantity_format_error');
				$this->error[] = $error;	
			}
		}
	}
	/// 查看
	public function view(){
		return $this->getInfoReturnSaleOrder($this->id);
	}
	/// 编辑
	public function edit(){
		return $this->getInfoReturnSaleOrder($this->id);
	}
	
	public function getInfoReturnSaleOrder($id){
		$rs = $this->find($id);  
		
		$sql	=	' 
				select a.*,(1-a.discount)*100 discount,    
							(a.quantity*a.capability*a.dozen) as sum_quantity , 
							(a.quantity*a.capability*a.dozen*a.price) as money,
							(a.quantity*a.capability*a.dozen*a.price*discount) discount_money
				from return_sale_order_detail as a
				where a.return_sale_order_id='.$id.'
				group by a.id order by id';  
		$rs['detail'] = $this->db->query($sql);   
		if (false === $rs || $rs == null) { // 记录不存在或没权限查看该记录
			halt(L('data_right_error'));
		} 
		$rs = _formatListRelation($rs);
		return $rs;
	}
	
	public function indexSql(){ 
		return $this->getReturnSaleOrderListSql(); 
	}
	
	private function getReturnSaleOrderListSql($where=null){
		$where && $where = ' and '.$where;
		$count 	= $this->exists('select 1 from return_sale_order_detail where return_sale_order_id=return_sale_order.id and '.getWhere($_POST['detail']))
						->where(getWhere($_POST['main']).$where)
						->count();
		$this->setPage($count);
		$ids			= $this->field('id')
								->exists('select 1 from return_sale_order_detail where return_sale_order_id=return_sale_order.id and '.getWhere($_POST['detail']))
								->where(getWhere($_POST['main']).$where)->order('return_sale_order_no desc')
								->page()
								->selectIds();
		$info['from']	= 'return_sale_order a left join return_sale_order_detail b on(a.id=b.return_sale_order_id) left join invoice_out c on a.id=c.relation_id and c.invoice_type=2 ';		
		$info['where']	= ' where a.id in '.$ids;
		$info['group']	= ' group by a.id order by a.return_sale_order_no desc';
		$info['field']	= ' a.*,count(distinct b.product_id) as product_qn,
						c.invoice_no,sum(if(invoice_state=2,0,1)) no_invoice,c.id as invoiceOut_id,
						b.capability as sum_capability,
						sum(b.quantity) as sum_qn,
						sum(b.quantity*b.capability*b.dozen) as sun_quantity, 
						sum(b.quantity*b.capability*b.dozen*b.price*discount) as money';
		return  'select '.$info['field'].' from '.$info['from'].$info['where'].$info['group']; 
	}
	
	public function setPost(){ 
		$info=	$_POST;
		$info['return_order_date_format']	=	formatDate($info['return_order_date'],'date');
		foreach ($info['detail'] as $k => $v) {  
			if (is_numeric($v['discount'])){
				$info['detail'][$k]['discount']	=	1-($v['discount']*0.01);
			}else{
				if (empty($v['discount'])){
					$info['detail'][$k]['discount']	=	1;
				}
			}
			if($v['product_id']>0){
				$product_id[]	= $v['product_id'];
			}
		}
		$info	= $this->setPrice($info,$product_id);  
		return $info; 
	}
	///计算 退货产品 成本单价
	public function setPrice($info,$product_id=array()){
		if(empty($product_id)||!is_array($product_id)){
			return $info;
		}
		$product_price	= M('product')->field('product_price.*,instock_price,product.id as product_id')
						->join('left join product_price  on product.id=product_price.product_id')
						->where('product.id in ('.implode(',',$product_id).')')
						->group('product.id')
						->select();
		foreach($product_price as $key=>$val){
			$tmp[$val['product_id']]	= $val;
		}
		$product_price	= $tmp;
		if($info['currency_id']!=C('currency')){
			$rate	= $this->getRate($info);
		}else{
			$rate['rate']	= 1;
		}
		foreach($info['detail'] as $key=>$val){
			if($val['product_id']>0){
				$price	= $product_price[$val['product_id']]['avg_price_'.$info['currency_id']];		//取平均单价
				if($price==0){
					$price	= $product_price[$val['product_id']]['instock_price'];		//取进货单价--因系统写死进货单价为RMB 本位币不是RMB 需取汇率换算成本位币
					if(C('currency')!=1){
						$tmp	= $info;
						$tmp['currency_id']	= 1;
						$rate	= $this->getRate($tmp);
						$price	*= $rate['rate'];
					}
					$rate['rate']	= 1;
					
				}
				$info['detail'][$key]['return_base_rate']=$rate['rate'];
				$info['detail'][$key]['return_base_price']	= $price;
				$_POST['detail'][$key]['return_base_price']	= $price;
//				$info['detail'][$key]['price_base_currency']= $POST['detail'][$key]['price_base_currency'] = $price*$rate['rate'];
				
			}
		}
		return $info;
	}
	
	///取汇率
	public function getRate($info){
		$currency_id	= intval(C('currency'));
		if($info['currency_id']>0){
			$rate_type	= C('set_rate_type');
			if($rate_type==2){
				$date	= date('Y-m',strtotime(formatDate($info['return_order_date'])));
				$rate 	= M('rate_info')->field('opened_y as rate')->where("rate_date='".$date."-01' and to_currency_id=".$currency_id." and from_currency_id=".$info['currency_id'])->find();
			}elseif($rate_type==3){
				$date	= date('Y-m-d',strtotime(formatDate($info['return_order_date'])));
				$rate	= M('rate_info')->field('opened_y as rate')->where("rate_date='".$date."' and to_currency_id=".$currency_id." and from_currency_id=".$info['currency_id'])->find();
			}
			if(empty($rate)){
				$rate	= M('fixed_rate')->field('rate')->where('to_currency_id='.$currency_id.' and from_currency_id='.$info['currency_id'])->find();
			}
		}else{
			$rate['rate']=1;
		}
		return $rate;
	}

	/**
	 * 退货
	 * @return unknown
	 */
	public function alistReturnOrderSql(){
		return $this->getReturnSaleOrderListSql('return_sale_order_type=1');
	}
	///换货
	public function alistSaleOrderSql(){
		return $this->getReturnSaleOrderListSql('return_sale_order_type=2');
	}
	///不可用产品
	public function returnNoUseList(){
		$groupBy	  = 'product_id';
		C('sale.color')==1 && $groupBy	.= ',color_id';
		C('sale.size')==1  && $groupBy	.= ',size_id';
		$info['from'] = 'return_sale_order_detail  ';
		$info['extend'] = 'where  '._search().' and is_use=2 group by '.$groupBy;
		$info['field'] = '*,
						sum(quantity) as sum_qn,
						sum(quantity*capability*dozen) as sun_quantity
						';
		$sql	= 'select '.$info['field'].' from '.$info['from'].' '.$info['extend']; 
		$count	=	0;
		$sql_count	= 'select count(*) as count '.' from '.$info['from'].' where  '._search().' and is_use=2 group by '.$groupBy; 
		$list	=	$this->query($sql_count);
		$count	=	$list[0]['count'];
		$info['sql']	=	$sql;
		$info['count']	=	$count; 
		$limit	= _page($count);
		return $this->indexList($limit,$sql);
	}
}